import { BaseLayer } from './BaseLayer';
import { Feature } from 'ol';
import { Geometry } from 'ol/geom';

/**
 * 图层管理器，用于统一管理所有图层
 */
export class LayerManager {
  private layers: Map<string, BaseLayer> = new Map();
  private groups: Map<string, Set<string>> = new Map();
  private tempLayers: Set<string> = new Set();
  
  /**
   * 注册图层
   * @param id 图层ID
   * @param layer 图层实例
   * @param isTemp 是否为临时图层
   */
  registerLayer(id: string, layer: BaseLayer, isTemp: boolean = false): void {
    if (this.layers.has(id)) {
      console.warn(`图层ID "${id}" 已存在，将覆盖原有图层`);
    }
    
    this.layers.set(id, layer);
    
    // 添加到临时图层集合
    if (isTemp) {
      this.tempLayers.add(id);
    }
    
    // 根据图层的group属性添加到分组
    const group = layer.getGroup();
    if (group) {
      this.addLayerToGroup(id, group);
    }
  }
  
  /**
   * 移除图层
   * @param id 图层ID
   */
  removeLayer(id: string): void {
    const layer = this.layers.get(id);
    if (!layer) return;
    
    // 从分组中移除
    const group = layer.getGroup();
    if (group) {
      this.removeLayerFromGroup(id, group);
    }
    
    // 从临时图层集合中移除
    this.tempLayers.delete(id);
    
    // 移除图层
    this.layers.delete(id);
    
    // 销毁图层
    layer.destroy();
  }
  
  /**
   * 获取图层
   * @param id 图层ID
   * @returns 图层实例或undefined
   */
  getLayer(id: string): BaseLayer | undefined {
    return this.layers.get(id);
  }
  
  /**
   * 获取所有图层
   * @returns 图层Map
   */
  getAllLayers(): Map<string, BaseLayer> {
    return this.layers;
  }
  
  /**
   * 添加图层到分组
   * @param layerId 图层ID
   * @param groupName 分组名称
   */
  addLayerToGroup(layerId: string, groupName: string): void {
    if (!this.groups.has(groupName)) {
      this.groups.set(groupName, new Set());
    }
    
    const group = this.groups.get(groupName);
    if (group) {
      group.add(layerId);
    }
    
    // 更新图层的group属性
    const layer = this.layers.get(layerId);
    if (layer) {
      layer.setGroup(groupName);
    }
  }
  
  /**
   * 从分组中移除图层
   * @param layerId 图层ID
   * @param groupName 分组名称
   */
  removeLayerFromGroup(layerId: string, groupName: string): void {
    const group = this.groups.get(groupName);
    if (group) {
      group.delete(layerId);
      
      // 如果分组为空，则移除分组
      if (group.size === 0) {
        this.groups.delete(groupName);
      }
    }
  }
  
  /**
   * 获取分组中的所有图层
   * @param groupName 分组名称
   * @returns 图层数组
   */
  getGroup(groupName: string): BaseLayer[] {
    const layerIds = this.groups.get(groupName);
    if (!layerIds) return [];
    
    const layers: BaseLayer[] = [];
    layerIds.forEach(id => {
      const layer = this.layers.get(id);
      if (layer) {
        layers.push(layer);
      }
    });
    
    return layers;
  }
  
  /**
   * 获取所有分组名称
   * @returns 分组名称数组
   */
  getAllGroups(): string[] {
    return Array.from(this.groups.keys());
  }
  
  /**
   * 显示/隐藏指定分组
   * @param groupName 分组名称
   * @param visible 是否可见
   */
  setGroupVisibility(groupName: string, visible: boolean): void {
    const layers = this.getGroup(groupName);
    layers.forEach(layer => {
      // 检查权限后设置可见性
      if (layer.checkPermission('visible')) {
        layer.setVisible(visible);
      }
    });
  }
  
  /**
   * 设置图层的层级顺序
   * @param layerId 图层ID
   * @param zIndex 层级值
   */
  setLayerZIndex(layerId: string, zIndex: number): void {
    const layer = this.layers.get(layerId);
    if (layer) {
      layer.setZIndex(zIndex);
    }
  }
  
  /**
   * 清理所有临时图层
   */
  clearTempLayers(): void {
    this.tempLayers.forEach(id => {
      this.removeLayer(id);
    });
    this.tempLayers.clear();
  }
  
  /**
   * 根据角色设置图层权限
   * @param role 角色名称
   * @param permissions 权限配置
   */
  setLayerPermissionsByRole(
    role: string,
    permissions: { [layerId: string]: { visible: boolean; editable: boolean } }
  ): void {
    // 修复forEach类型错误
    const permissionEntries = Object.entries(permissions) as Array<[string, { visible: boolean; editable: boolean }]>;
    permissionEntries.forEach(([layerId, permission]) => {
      const layer = this.layers.get(layerId);
      if (layer) {
        layer.setPermissions(permission);
      }
    });
  }
  
  /**
   * 获取当前用户可编辑的图层
   * @returns 可编辑的图层数组
   */
  getEditableLayers(): BaseLayer[] {
    const editableLayers: BaseLayer[] = [];
    
    this.layers.forEach((layer, id) => {
      if (layer.checkPermission('editable')) {
        editableLayers.push(layer);
      }
    });
    
    return editableLayers;
  }
}